// src/services/categories.js - 分区管理服务

import { get } from './api';
import {
  getAllCategories as localGetAllCategories,
  getTorrentsByCategory as localGetTorrentsByCategory,
  initCategories
} from '../utils/localStorage';

/**
 * 初始化分区数据
 */
export const initCategoriesData = () => {
  initCategories();
};

/**
 * 获取所有分区
 * @returns {Promise} - 分区列表
 */
export const getCategories = async () => {
  try {
    const response = await get('/categories');
    return response;
  } catch (error) {
    console.warn('获取分区列表API连接失败，使用本地存储:', error);

    const categories = localGetAllCategories();
    return {
      success: true,
      data: { categories }
    };
  }
};

/**
 * 获取分区内的资源
 * @param {string} categoryName - 分区名称
 * @param {Object} params - 查询参数
 * @returns {Promise} - 资源列表
 */
export const getCategoryResources = async (categoryName, params = {}) => {
  try {
    const query = new URLSearchParams();
    if (params.page) query.append('page', params.page);
    if (params.limit) query.append('limit', params.limit);
    if (params.sort) query.append('sort', params.sort);

    const queryString = query.toString();
    const endpoint = queryString ? `/categories/${categoryName}/resources?${queryString}` : `/categories/${categoryName}/resources`;

    const response = await get(endpoint);
    return response;
  } catch (error) {
    console.warn('获取分区资源API连接失败，使用本地存储:', error);

    const torrents = localGetTorrentsByCategory(categoryName);

    // 排序
    let sortedTorrents = torrents;
    const sortBy = params.sort || 'uploadDate';

    sortedTorrents.sort((a, b) => {
      switch (sortBy) {
        case 'uploadDate':
          return new Date(b.uploadDate) - new Date(a.uploadDate);
        case 'downloads':
          return (b.downloads || 0) - (a.downloads || 0);
        case 'seeders':
          return (b.seeders || 0) - (a.seeders || 0);
        case 'likes':
          return (b.likes || 0) - (a.likes || 0);
        case 'size':
          // 简单的大小排序，假设大小格式为 "X.X GB" 或 "X MB"
          const sizeA = parseSize(a.size);
          const sizeB = parseSize(b.size);
          return sizeB - sizeA;
        default:
          return 0;
      }
    });

    // 简单分页
    const page = params.page || 1;
    const limit = params.limit || 20;
    const start = (page - 1) * limit;
    const end = start + limit;
    const paginatedTorrents = sortedTorrents.slice(start, end);

    return {
      success: true,
      data: {
        torrents: paginatedTorrents,
        total: sortedTorrents.length,
        page: page,
        limit: limit,
        category: categoryName
      }
    };
  }
};

/**
 * 解析文件大小字符串为数字（MB）
 * @param {string} sizeStr - 大小字符串如 "1.5 GB", "500 MB"
 * @returns {number} - 大小（MB）
 */
const parseSize = (sizeStr) => {
  if (!sizeStr) return 0;

  const match = sizeStr.match(/(\d+(?:\.\d+)?)\s*(GB|MB|TB)/i);
  if (!match) return 0;

  const size = parseFloat(match[1]);
  const unit = match[2].toUpperCase();

  switch (unit) {
    case 'TB':
      return size * 1024 * 1024;
    case 'GB':
      return size * 1024;
    case 'MB':
      return size;
    default:
      return 0;
  }
};

/**
 * 获取分区统计信息
 * @param {string} categoryName - 分区名称
 * @returns {Promise} - 统计信息
 */
export const getCategoryStats = async (categoryName) => {
  try {
    const response = await get(`/categories/${categoryName}/stats`);
    return response;
  } catch (error) {
    console.warn('获取分区统计API连接失败，使用本地存储:', error);

    const torrents = localGetTorrentsByCategory(categoryName);

    const stats = {
      totalResources: torrents.length,
      totalSize: torrents.reduce((total, torrent) => total + parseSize(torrent.size), 0),
      totalDownloads: torrents.reduce((total, torrent) => total + (torrent.downloads || 0), 0),
      totalSeeders: torrents.reduce((total, torrent) => total + (torrent.seeders || 0), 0),
      totalLeechers: torrents.reduce((total, torrent) => total + (torrent.leechers || 0), 0),
      recentUploads: torrents.filter(torrent => {
        const uploadDate = new Date(torrent.uploadDate);
        const oneWeekAgo = new Date();
        oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
        return uploadDate > oneWeekAgo;
      }).length
    };

    return {
      success: true,
      data: { stats }
    };
  }
};

export default {
  initCategoriesData,
  getCategories,
  getCategoryResources,
  getCategoryStats
}; 